//
//  RentHouseViewController.m
//  Liuhe
//
//  Created by zr on 2018/8/7.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "RentHouseViewController.h"
#import "RentHouseTableViewCell.h"
#import "RentHouseInfoViewController.h"
#import "PushHouseInfoViewController.h"
#import "RentHouseHeader.h"
#import "RentHouseTopView.h"
#import "RentHouseModel.h"

@interface RentHouseViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)RentHouseTopView * topview;
@property (nonatomic, weak)UITextField * searchTextfiled;
@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)UIButton *button;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, strong)NSArray<RentHouseModel *> * rentModelArray;
@property (nonatomic, strong)RentHouseHeader * rentHeader;
@property (nonatomic, copy)NSString * type;

@end

@implementation RentHouseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = WHITE_COLOR;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showTopTableView:) name:@"showTopTableView" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RemoveTopTableView:) name:@"RemoveTopTableView" object:nil];
    
    [RentHouseModel rentModelWithDict:nil WithSucess:^(NSArray<RentHouseModel *> *array) {
        
        self.rentModelArray = array;
    } error:^{
        
    }];
    
    [self setupNav];
    [self performSelector:@selector(createButton) withObject:nil afterDelay:0];
    [self setupUI];

}


- (void)setRentModelArray:(NSArray<RentHouseModel *> *)rentModelArray{
    
    _rentModelArray = rentModelArray;
    
    [self.tableView reloadData];
}


- (void)setupNav{
    
    self.title = @"房屋租赁";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(0, 0, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
}

- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)setupUI{
    
    UITextField * searchTextfiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 5 * SCREENH6, 260 * SCREENH6, 30 * SCREENH6)];
    
    searchTextfiled.borderStyle = UITextBorderStyleRoundedRect;
    searchTextfiled.backgroundColor = [UIColor whiteColor];
    //设置光标颜色
    searchTextfiled.tintColor = [UIColor whiteColor];
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xbebebe);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    searchTextfiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入楼盘或区域" attributes:attrs];
    searchTextfiled.textColor = [UIColor blackColor];
    searchTextfiled.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    searchTextfiled.leftViewMode = UITextFieldViewModeAlways;
    searchTextfiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    UIView * rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 20 * SCREENH6)];
    UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(5, 0, 16 * SCREENH6, 17.5 * SCREENH6)];//WithImage:[UIImage imageNamed:@"手机号"]];
    image.image = ImageNamed(@"hg");
    [rightView addSubview:image];
    searchTextfiled.leftView = rightView;
    searchTextfiled.leftViewMode = UITextFieldViewModeAlways;
    searchTextfiled.returnKeyType = UIReturnKeySearch;
    searchTextfiled.delegate = self;
    
    self.searchTextfiled = searchTextfiled;
    
    //    [view addSubview:self.searchTextfiled];
    
    self.navigationItem.titleView = self.searchTextfiled;
    
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT - 40) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.rowHeight = 116 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[RentHouseTableViewCell class] forCellReuseIdentifier:@"RentHouseListCell"];
    [self.tableView registerClass:[RentHouseHeader class] forHeaderFooterViewReuseIdentifier:@"RentHouseView"];
    
    [self.view addSubview:self.tableView];
    
}


- (void)createButton{
    
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setImage:ImageNamed(@"fb") forState:UIControlStateNormal];
    
    _button.frame = CGRectMake(SCREEN_WIDTH - 50 * SCREENH6, SCREENH_HEIGHT - 200 * SCREENH6, 45 * SCREENH6, 45 * SCREENH6);
    _button.adjustsImageWhenHighlighted = NO;
    [_button addTarget:self action:@selector(resignButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_button];
    
    //放一个拖动手势，用来改变控件的位置
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changePostion:)];
    
    [_button addGestureRecognizer:pan];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return self.rentModelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RentHouseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RentHouseListCell" forIndexPath:indexPath];
    
    cell.model = self.rentModelArray[indexPath.row];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HIDDEN_TAB;
    
    RentHouseInfoViewController * infoVC = [RentHouseInfoViewController new];
    
    RentHouseModel * model = self.rentModelArray[indexPath.row];
    
    infoVC.model = model;
    
    [self.navigationController pushViewController:infoVC animated:YES];
    
    SHOW_TAB;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 47* SCREENH6;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    self.rentHeader = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"RentHouseView"];
    
    return self.rentHeader;
}


- (void)resignButton{
    
    HIDDEN_TAB;
    
    PushHouseInfoViewController * pushVC = [PushHouseInfoViewController new];
    
    [self.navigationController pushViewController:pushVC animated:YES];
}

//手势事件 －－ 改变位置

-(void)changePostion:(UIPanGestureRecognizer *)pan{
    
    CGPoint point = [pan translationInView:_button];
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    
    CGRect originalFrame = _button.frame;
    
    if (originalFrame.origin.x >= 0 && originalFrame.origin.x+originalFrame.size.width <= width) {
        
        originalFrame.origin.x += point.x;
        
    }if (originalFrame.origin.y >= 0 && originalFrame.origin.y+originalFrame.size.height <= height) {
        
        originalFrame.origin.y += point.y;
        
    }
    
    _button.frame = originalFrame;
    
    [pan setTranslation:CGPointZero inView:_button];
    
    if (pan.state == UIGestureRecognizerStateBegan) {
        
        _button.enabled = NO;
        
    }else if (pan.state == UIGestureRecognizerStateChanged){
        
    } else {
        
        CGRect frame = _button.frame;
        
        //是否越界
        
        BOOL isOver = NO;
        
        if (frame.origin.x < 0) {
            
            frame.origin.x = 0;
            
            isOver = YES;
            
        } else if (frame.origin.x+frame.size.width > width) {
            
            frame.origin.x = width - frame.size.width;
            
            isOver = YES;
            
        }if (frame.origin.y < 0) {
            
            frame.origin.y = 0;
            
            isOver = YES;
            
        } else if (frame.origin.y+frame.size.height > height) {
            
            frame.origin.y = height - frame.size.height;
            
            isOver = YES;
            
        }if (isOver) {
            
            [UIView animateWithDuration:0.3 animations:^{
                
                self->_button.frame = frame;
                
            }];
            
        }
        
        _button.enabled = YES;
        
    }
    
}


- (void)showTopTableView:(NSNotification *)noti{
    
    self.button.hidden = YES;
    
    self.type = noti.userInfo[@"type"];
        
    self.topview = [[RentHouseTopView alloc] initWithFrame:CGRectMake(0, 47 * SCREENH6, SCREEN_WIDTH, 341 * SCREENH6)];
    
    self.topview.type = self.type;
    
    [self.view addSubview:self.topview];
    
    UIView * bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 388 * SCREENH6, SCREEN_WIDTH, 212 * SCREENH6)];
    
    bottomView.backgroundColor = BLACK_COLOR;
    bottomView.alpha = 0.2;
    
    self.bottomView = bottomView;
    
    [self.view addSubview:self.bottomView];
   
}


- (void)RemoveTopTableView:(NSNotification *)noti{
    
    NSString * style = noti.userInfo[@"type"];
    
    
    self.button.hidden = NO;
    [self.topview removeFromSuperview];
    [self.bottomView removeFromSuperview];
    
    if ([style isEqualToString:@"sure"]) {
        
        NSString * string = noti.userInfo[@"string"];
        
        NSDictionary * dict = @{self.type:string};
        self.rentHeader.dict = dict;
        
        [RentHouseModel rentModelWithDict:dict WithSucess:^(NSArray<RentHouseModel *> *array) {
            
            self.rentModelArray = array;
        } error:^{
            
        }];
    }
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
